<script lang="ts" setup>
import { ref, computed, markRaw, watch } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import createStep1 from './components/createStep1.vue';
import createStep2 from './components/createStep2.vue';
import createStep3 from './components/createStep3.vue';
import { store } from '@/store';
import API from '@/services';
import { useRouter } from 'vue-router';
import * as RouteNames from '@/router/consts';
import { bindType } from '@/hooks/base';

const currentComponent = ref<any>(markRaw(createStep1));
const currentComponentRef = ref('createStep1Child');
const emit = defineEmits(['update']);
const router = useRouter();
const visible = ref(false);
const currentStep = computed(() => store.state.scenesManage.currentStep);
const createStep1Child = ref();
const createStep2Child = ref();
const createStep3Child = ref();
const isEdit = ref(false);
const sceneId = computed(() => store.state.scenesManage.sceneId);
const useTableId = computed(() => store.state.scenesManage.step1UseTableId);
const step1Data = computed(() => store.state.scenesManage.formStep1Data);
const step2Data = computed(() => store.state.scenesManage.formStep2Data);
const step3Data = computed(() => store.state.scenesManage.formStep3Data);
const form = computed(() => store.state.scenesManage.formStep1Data);
const isCheck = ref(false);
// 获取api
const {
  scene: { getSceneById, postScene, putSceneById, getSceneJudgeInfo }
} = API;

watch(useTableId, (newVal, oldVal) => {
  if (newVal) {
    form.value.tableSource = newVal;
    store.commit('scenesManage/saveFormStep1Data', form.value);
  }
});

const showDrawer = (id?: number) => {
  if (id) {
    // 编辑获取数据
    isEdit.value = true;
    fetchSceneById(id);
  }
  currentComponent.value = markRaw(createStep1);
  currentComponentRef.value = 'createStep1Child';
  visible.value = true;
};

// 点击编辑(获取当前场景的相关信息)
const fetchSceneById = (id: number) => {
  getSceneById({ id: id }).then((res: any) => {
    if (res.code === 200) {
      let step1Data = {
        cnName: res.data?.cnName,
        sceneColorType: res.data?.sceneColorType,
        path: res.data?.path,
        description: res.data?.description,
        tableSource: String(res.data?.tableSource),
        groupId: res.data?.groupId
      };
      console.log('走到编辑');
      checkStep3Data(id, res.data?.tableSource);
      store.commit('scenesManage/setSceneId', res.data?.id);
      store.commit(
        'scenesManage/changeStep1UseTableId',
        String(res.data?.tableSource)
      );
      store.commit('scenesManage/saveFormStep1Data', step1Data);
      store.commit('scenesManage/saveFormStep2Data', res.data?.list);
    }
  });
};

// 点击取消
const onCancle = () => {
  Modal.confirm({
    modalClass: 'model-message-confirm',
    title: '提示',
    content: '取消后，填写的内容不做保存，不可恢复',
    simple: false,
    closable: false,
    hideCancel: true,
    okText: '我知道了',
    onBeforeOk: (done) => {
      resetData();
      visible.value = false;
      done(true);
    }
  });
};

// 点击暂存
const onStorage = async () => {
  if (currentStep.value === 1) {
    let result = null;
    result = await createStep1Child.value.checkForm();
    if (!result) {
      return;
    }
  }
  if (currentStep.value === 3) {
    createStep3Child.value.saveData();
  }
  // 确认：0，暂存分两种情况，第三步没有选指标：2，第三步选中指标、维度等：3"
  let confirmStatus = 0;
  console.log(step3Data.value, '第三步数据');
  // todo: 后台还差个接口 用来判断第三步是否有数据 优先判断接口返回 再判断本地存的那个
  if (step3Data.value.length || isCheck.value) {
    confirmStatus = 3;
  } else {
    confirmStatus = 2;
  }
  if (isEdit.value) {
    editSceneSave(confirmStatus, 'storage');
  } else {
    creatSceneSave(confirmStatus, 'storage');
  }
};

// 点击上一步
const onPrevious = () => {
  store.commit('scenesManage/changeCurrentStep', currentStep.value - 1);
  switch (currentStep.value) {
    case 1:
      currentComponent.value = markRaw(createStep1);
      currentComponentRef.value = 'createStep1Child';
      createStep2Child.value.saveData();
      setTimeout(() => {
        createStep1Child.value.changeUseTable(useTableId.value);
      }, 500);
      break;
    case 2:
      currentComponent.value = markRaw(createStep2);
      currentComponentRef.value = 'createStep2Child';
      createStep3Child.value.saveData();
      break;
    case 3:
      currentComponent.value = markRaw(createStep3);
      currentComponentRef.value = 'createStep3Child';
      break;
  }
};

// 点击下一步
const onNext = async () => {
  let result = null;
  if (currentStep.value === 1) {
    result = await createStep1Child.value.checkForm();
    createStep1Child.value.saveData();
  }
  if (currentStep.value === 2) {
    createStep2Child.value.saveData();
    store.commit('scenesManage/changeStep1UseTable', false);
    result = true;
  }
  if (result) {
    store.commit('scenesManage/changeCurrentStep', currentStep.value + 1);
    switch (currentStep.value) {
      case 1:
        currentComponent.value = markRaw(createStep1);
        currentComponentRef.value = 'createStep1Child';
        break;
      case 2:
        currentComponent.value = markRaw(createStep2);
        currentComponentRef.value = 'createStep2Child';
        break;
      case 3:
        currentComponent.value = markRaw(createStep3);
        currentComponentRef.value = 'createStep3Child';
        break;
    }
  }
};

// 点击确认
const onSubmit = () => {
  if (currentStep.value === 3) {
    createStep3Child.value.saveData();
  }
  if (!step3Data.value.length) {
    Message.error('请勾选要绑定的指标/维度');
    return;
  }
  if (isEdit.value) {
    editSceneSave(0, 'save');
  } else {
    creatSceneSave(0, 'save');
  }
};

// 将存储的数据清空
const resetData = () => {
  store.commit('scenesManage/resetFormStep1');
  store.commit('scenesManage/resetFormStep2');
  store.commit('scenesManage/resetFormStep3');
  store.commit('scenesManage/resetUseTableId');
  store.commit('scenesManage/resetSceneId');
  store.commit('scenesManage/changeCurrentStep', 1);
  store.commit('scenesManage/resetSelectedTableStep3');
  isEdit.value = false;
};

// 创建场景时的暂存/保存
const creatSceneSave = (confirmStatus: number, path: string) => {
  if (currentStep.value === 2) {
    createStep2Child.value.saveData();
  }
  if (currentStep.value === 3) {
    createStep3Child.value.saveData();
  }
  let isPermission = confirmStatus === 0 ? checkData(step3Data.value) : true;
  if (isPermission) {
    let params = {
      cnName: step1Data.value.cnName,
      columnDetailDTOList: step3Data.value || [],
      confirm: confirmStatus,
      description: step1Data.value.description,
      groupId: step1Data.value.groupId,
      list: step2Data.value || [],
      sceneColorType: step1Data.value.sceneColorType,
      tableSource: step1Data.value.tableSource
    };
    postScene({ ...params })
      .then((res: any) => {
        if (res.code === 200) {
          if (path === 'storage') {
            Message.success('暂存成功');
          }
          if (path === 'save') {
            Message.success('创建成功');
          }
          visible.value = false;
          resetData();
          emit('update');
          router.push({ name: RouteNames.ROUTE_INDEXSCENESMANAGE });
        }
      })
      .catch(() => {});
  }
};

// 编辑场景时的暂存/保存
const editSceneSave = (confirmStatus: number, path: string) => {
  if (currentStep.value === 2) {
    createStep2Child.value.saveData();
  }
  if (currentStep.value === 3) {
    createStep3Child.value.saveData();
  }
  let isPermission = confirmStatus === 0 ? checkData(step3Data.value) : true;
  if (isPermission) {
    let params = {
      cnName: step1Data.value.cnName,
      columnDetailDTOList: step3Data.value || [],
      confirm: confirmStatus,
      description: step1Data.value.description,
      groupId: step1Data.value.groupId,
      list: step2Data.value || [],
      sceneColorType: step1Data.value.sceneColorType,
      tableSource: step1Data.value.tableSource
    };
    putSceneById({ id: sceneId.value }, { ...params })
      .then((res: any) => {
        if (res.code === 200) {
          if (path === 'storage') {
            Message.success('暂存成功');
          }
          if (path === 'save') {
            Message.success('保存成功');
          }
          visible.value = false;
          resetData();
          emit('update');
          router.push({ name: RouteNames.ROUTE_INDEXSCENESMANAGE });
        }
      })
      .catch(() => {});
  }
};

// 校验第三步数据
const checkData = (data: any) => {
  if (!data.length && currentStep.value === 3) {
    Message.error('请勾选要绑定的指标/维度');
    return;
  }
  let timePeriodArr = data?.filter(
    (item: any) => item.columnType == bindType.TIMEPERIOD
  );
  let metricsArr = data?.filter(
    (item: any) => item.columnType == bindType.METRICS
  );
  let dimensionArr = data?.filter(
    (item: any) => item.columnType == bindType.DIMENSION
  );
  if (!data.length && currentStep.value === 3) {
    Message.error('请勾选要绑定的指标/维度');
    return false;
  } else if (timePeriodArr.length > 1) {
    Message.error('只可以绑定一个统计粒度');
    return false;
  } else if (!timePeriodArr.length) {
    Message.error('必须绑定一个统计粒度');
    return false;
  } else if (!metricsArr.length) {
    Message.error('至少绑定一个指标');
    return false;
  } else if (!dimensionArr.length) {
    Message.error('至少绑定一个维度');
    return false;
  } else {
    return true;
  }
};

// 走接口校验第三步数据有无
const checkStep3Data = async (sceneId: any, useTableId: any) => {
  getSceneJudgeInfo({
    sceneId: sceneId,
    tableId: useTableId
  }).then((res) => {
    isCheck.value = res.data as boolean;
  });
};

defineExpose({ showDrawer });
</script>

<template>
  <a-drawer
    :visible="visible"
    unmountOnClose
    class="scenes-drawer"
    width="850px"
    @cancel="onCancle"
  >
    <template #title>
      <span
        style="font-weight: bold; font-size: 16px"
        v-html="isEdit ? '编辑场景' : '创建场景'"
      ></span>
    </template>
    <div class="scenes-drawer-content">
      <a-steps
        label-placement="vertical"
        :current="currentStep"
        style="margin-top: 8px"
      >
        <a-step class="step-title">基本信息</a-step>
        <a-step class="step-title">维表关联（选填）</a-step>
        <a-step class="step-title">绑定指标/维度</a-step>
      </a-steps>
      <div class="scenes-drawer-content-form-wrap">
        <component
          :is="currentComponent"
          :ref="currentComponentRef"
        ></component>
      </div>
    </div>
    <template #footer>
      <div class="scenes-drawer-footer">
        <a-button type="outline" @click="onCancle">取消</a-button>
        <a-button type="outline" @click="onStorage">暂存</a-button>
        <a-button type="primary" @click="onPrevious" v-show="currentStep > 1"
          >上一步</a-button
        >
        <a-button
          type="primary"
          @click="onNext"
          v-show="currentStep > 0 && currentStep < 3"
          >下一步</a-button
        >
        <a-button type="primary" @click="onSubmit" v-show="currentStep === 3"
          >确认</a-button
        >
      </div>
    </template>
  </a-drawer>
</template>

<style lang="scss" scoped>
.scenes-drawer {
  ::v-deep(.arco-drawer-header) {
    .arco-drawer-close-btn {
      font-size: 16px;
    }
  }
  &-content {
    .step-title {
      ::v-deep(.arco-steps-item-title) {
        font-size: 12px;
        height: 20px;
        line-height: 20px;
      }
    }
    &-form-wrap {
      margin-top: 28px;
    }
  }
  &-footer {
    display: flex;
    justify-content: flex-end;
    .arco-btn {
      margin-left: 12px;
      &:first-child {
        border-color: #d4d7e1;
        color: #33353b;
      }
    }
  }
}
</style>
